#include <sw/redis++/redis.h>
#include <gflags/gflags.h>
#include <iostream>
#include <thread>

DEFINE_string(ip,"127.0.0.1","这是服务器的IP地址");
DEFINE_int32(port,6379,"这是服务器的端口");
DEFINE_int32(db,0,"库的编号");
DEFINE_bool(keep_alive,true,"是否进行长连接保活");

void print(sw::redis::Redis& client)
{
    auto user1 = client.get("会话001");
    if(user1) std::cout << *user1 <<std::endl; 
    auto user2 = client.get("会话002");
    if(user2) std::cout << *user2 <<std::endl; 
    auto user3 = client.get("会话003");
    if(user3) std::cout << *user3 <<std::endl; 
    auto user4 = client.get("会话004");
    if(user4) std::cout << *user4 <<std::endl; 
    auto user5 = client.get("会话005");
    if(user5) std::cout << *user5 <<std::endl; 
    auto user6 = client.get("会话006");
    if(user6) std::cout << *user6 <<std::endl; 
}


void add_string(sw::redis::Redis& client) {
    client.set("会话001","用户001");
    client.set("会话002","用户002");
    client.set("会话003","用户003");
    client.set("会话004","用户004");
    client.set("会话005","用户005");
    client.set("会话006","用户006");

    //删除key
    client.del("会话003");

    //修改对应的key
    client.set("会话004","12111211");

    print(client);

}


void expired_test(sw::redis::Redis& client) {
    client.set("会话005","用户555555",std::chrono::milliseconds(1000));
    print(client);
    std::cout << "1s后" << std::endl;
    std::this_thread::sleep_for(std::chrono::seconds(2));
    print(client);
}

void list_test(sw::redis::Redis& client) {
    client.rpush("1","成员1");
    client.rpush("1","成员2");
    client.rpush("1","成员3");
    client.rpush("1","成员4");
    client.rpush("1","成员5");
    client.rpush("1","成员6");

    std::vector<std::string> users;
    client.lrange("1",0,-1,std::back_inserter(users));
    for(auto e : users) 
    {
        std::cout << e << std::endl;
    }

    std::cout << client.type("1") << std::endl;

    client.del("1");

    std::cout << client.type("1") << std::endl;

}

int main(int argc,char* argv[])
{
    google::ParseCommandLineFlags(&argc,&argv,true);
    sw::redis::ConnectionOptions opts;
    opts.host = FLAGS_ip;
    opts.port = FLAGS_port;
    opts.db = FLAGS_db;
    opts.keep_alive = FLAGS_keep_alive;
    //创建客户端对象
    sw::redis::Redis client(opts);
    add_string(client);

    std::cout << std::endl;
    expired_test(client);
    
    std::cout << "--------------------------" << std::endl;
    list_test(client);

    return 0;
}
